package com.piece.mall.controller;

import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.collection.MapUtil;
import com.piece.core.framework.util.file.ImageUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.file.client.FileClientFactory;
import com.piece.file.model.TbSysFile;
import com.piece.file.service.TbSysFileService;
import com.piece.mall.model.PmsBrand;
import com.piece.mall.service.PmsBrandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
@Api(tags = {"商品品牌管理"})
@RequestMapping("/api/mall/brand")
public class PmsBrandController extends FrameWorkController {

    @Resource
    private PmsBrandService pmsBrandService;

    @Resource
    private TbSysFileService tbSysFileService;

    @Autowired
    private FileClientFactory fileClientFactory;

    @PostMapping("/list")
    @AclPermission(code = "mall:brand:view")
    @ApiOperation(value = "查询品牌列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = pmsBrandService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "mall:brand:view")
    @ApiOperation(value = "查询品牌分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = pmsBrandService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "mall:brand:view")
    @ApiOperation(value = "加载品牌表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        PmsBrand pmsBrand = new PmsBrand();
        if (id != 0) {
            pmsBrand = pmsBrandService.findById(id);
        } else {
            pmsBrand.setShowStatus(StatusType.NORMAL.getCode());
            pmsBrand.setBrandSort(pmsBrandService.findNextCategorySort());
        }
        return success(pmsBrand);
    }

    @SubmitPermission
    @PostMapping("/uploadLogoFinal")
    @ApiOperation(value = "上传logo")
    @ApiImplicitParam(name = "avatar_file", value = "logo")
    public AjaxResponse uploadThumbnailFinal(@RequestParam("avatar_file") MultipartFile file) {
        if (file != null) {
            try {
                InputStream is = file.getInputStream();
                byte[] bytes = ImageUtil.scale(is, 1024);
                TbSysFile sysFile = fileClientFactory.get().writeToStore(bytes, "logo", file.getOriginalFilename(), file.getSize());
                return success(sysFile.getFileId());
            } catch (Exception e) {
                return error(I18nUtil.message(ExceptionConstants.UPLOAD_ERROR), e.getMessage());
            }
        }
        return error(I18nUtil.message(ExceptionConstants.NO_SELECT));
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "mall:brand:edit")
    @ApiOperation(value = "保存品牌表单数据")
    @ApiImplicitParam(value = "品牌数据", dataTypeClass = PmsBrand.class, type = "body")
    public AjaxResponse save() {
        PmsBrand pmsBrand;
        try {
            Long id = Convert.toLong(getRequest().getParameter("id"));
            String oldLogo = "";
            String logo = getRequest().getParameter("logo");
            if (null != id) {
                pmsBrand = pmsBrandService.findById(id);
                oldLogo = pmsBrand.getLogo();
                // 删除原logo
                if (!StringUtil.equals(oldLogo, logo)) {
                    tbSysFileService.deleteByTableAndBusinessList(PmsBrand.class.getSimpleName(), Convert.toStrList(pmsBrand.getBrandId() + ""));
                }
            } else {
                pmsBrand = new PmsBrand();
            }
            initDB(pmsBrand);
            pmsBrandService.insertOrUpdate(pmsBrand);

            if (!StringUtil.equals(oldLogo, logo) && StringUtil.isNotEmpty(logo)) {
                TbSysFile file = tbSysFileService.findById(logo);
                if (null != file) {
                    file.setTable(PmsBrand.class.getSimpleName());
                    file.setBusinessId(Convert.toStr(pmsBrand.getBrandId()));
                    tbSysFileService.update(file);
                }
            }

            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "mall:brand:delete")
    @ApiOperation(value = "删除品牌数据")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse delete(@PathVariable String id) throws Exception {
        PmsBrand brand = pmsBrandService.findById(id);
        String logo = brand.getLogo();
        pmsBrandService.delete(id);
        if (StringUtil.isNotEmpty(logo)) {
            deleteLogo(logo);
        }

        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "mall:brand:delete")
    @ApiOperation(value = "删除品牌数据")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse deleteBatch() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            List<PmsBrand> brands = pmsBrandService.findByCondition(MapUtil.builder(new HashMap<String, Object>())
                    .put("Q_brandId_L_IN", Convert.toLongArray(ids))
                    .build());
            pmsBrandService.delete(Convert.toLongArray(ids));
            brands.stream().forEach(brand -> {
                String logo = brand.getLogo();
                if (StringUtil.isNotEmpty(logo)) {
                    deleteLogo(logo);
                }
            });
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    // 删除logo图
    private void deleteLogo(String fileId) {
        TbSysFile file = tbSysFileService.findById(fileId);
        try {
            fileClientFactory.get().deleteFile(file);
        } catch (Exception e) {
            log.error("删除文件失败", e);
        }
    }
}
